/*
 * @(#)ListWorkflowRecordAction.java
 *
 * Copyright (c) 2003 DCIVision Ltd
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of DCIVision
 * Ltd ("Confidential Information").  You shall not disclose such Confidential
 * Information and shall use it only in accordance with the terms of the license
 * agreement you entered into with DCIVision Ltd.
 */
package com.dcivision.workflow.web;

import java.sql.Connection;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.quartz.SchedulerException;

import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.ErrorConstant;
import com.dcivision.framework.GlobalConstant;
import com.dcivision.framework.SessionContainer;
import com.dcivision.framework.SystemFunctionConstant;
import com.dcivision.framework.TextUtility;
import com.dcivision.framework.Utility;
import com.dcivision.framework.web.AbstractListAction;
import com.dcivision.framework.web.AbstractSearchForm;
import com.dcivision.workflow.WorkflowErrorConstant;
import com.dcivision.workflow.bean.WorkflowGroup;
import com.dcivision.workflow.bean.WorkflowRecord;
import com.dcivision.workflow.bean.WorkflowScheduleTriggers;
import com.dcivision.workflow.core.WorkflowStepManager;
import com.dcivision.workflow.dao.WorkflowGroupDAObject;
import com.dcivision.workflow.dao.WorkflowRecordDAObject;
import com.dcivision.workflow.dao.WorkflowScheduleTriggersDAObject;


/**
 * <p>Class Name:       ListWorkflowRecordAction.java    </p>
 * <p>Description:      The list action class for ListWorkflowRecord.jsp</p>
 * @author           Angus Shiu
 * @company          DCIVision Limited
 * @creation date    30/07/2003
 * @version          $Revision: 1.13.2.1 $
 */
public class ListWorkflowRecordAction extends AbstractListAction {

  public static final String REVISION = "$Revision: 1.13.2.1 $";

  
  /** Creates a new instance of ListWorkflowRecordAction */
  public ListWorkflowRecordAction() {
    super();
    this.setListName("workflowRecordList");
  }
  
  /** getFunctionCode
   *
   * Abstract function which sub-class should implement to return the corresponding
   * function code.
   *
   * @return   The function code
   */
  public String getFunctionCode() {
    return(SystemFunctionConstant.WORKFLOW_RECORD);
  }
  
  /** getMajorDAOClassName
   *
   * Abstract function which sub-class should implement to return the corresponding
   * major DAO class name used in this class.
   *
   * @return   The DAO class name
   */
  public String getMajorDAOClassName() {
    return("com.dcivision.workflow.dao.WorkflowRecordDAObject");
  }
  
  /**
   * setPageTitle
   * set the extend page title and page path.
   * default page path/title will be created by navmode and functionCode
   */
  public void setPageTitle(HttpServletRequest request, HttpServletResponse response, ActionForm form, ActionMapping mapping, ActionForward actionForward){
    String extendTitle = ( (WorkflowGroup)request.getAttribute("workflowGroup")).getGroupName();
    request.setAttribute(GlobalConstant.EXTEND_PAGE_TITLE, extendTitle);
    request.setAttribute(GlobalConstant.EXTEND_PAGE_TITLE_SHOW_ONLY, new Boolean(true));
  }
  public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws ServletException {
    AbstractSearchForm searchForm = (AbstractSearchForm)form;
    log.info(this.getClass().getName()+", OP Mode:"+searchForm.getOpMode()+", Nav Mode:"+searchForm.getNavMode());
//  Set the function code for current action.
    ActionForward forward = this.retrieveFunctionCode(request, response, mapping);
    if (forward!=null) {
      return forward;
    }
    if (GlobalConstant.OP_MODE_LIST_DELETE.equals(searchForm.getOpMode())) {
      WorkflowRecordDAObject recordDAO = new WorkflowRecordDAObject(this.getSessionContainer(request), this.getConnection(request));
      String[] selectedID = searchForm.getBasicSelectedID();
      boolean isDelete = true;
      for (int i = 0; i < selectedID.length; i++ ) {
        WorkflowRecord currentRecord = (WorkflowRecord) recordDAO.getObjectByID(new Integer(selectedID[i]));
        if(WorkflowRecord.WORKFLOW_RECORD_RELEASE.equals(currentRecord.getStatus())) {
          addError(request, ErrorConstant.WORKFLOW_RELEASED_RECORD_CAN_NOT_DELETED);
          isDelete = false;
          break;
        }
      }
      if (isDelete) {
        return super.execute(mapping, form, request, response);
      } else {
        searchForm.setBasicSelectedID(null);
        searchForm.setOpMode(null);

        // Check for all item deletes per page
        this.getListData(mapping, searchForm, request, response);
        return mapping.findForward(GlobalConstant.NAV_MODE_LIST);
      }
      
    } else {
      return super.execute(mapping, form, request, response);
    }
  }
  
  public void getListData(ActionMapping mapping, AbstractSearchForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
    SessionContainer sessionContainer = this.getSessionContainer(request);
    Connection conn = this.getConnection(request);
    ListWorkflowRecordForm workflowSearchForm = (ListWorkflowRecordForm) form;
    WorkflowGroupDAObject wfGroupDAO = new WorkflowGroupDAObject(sessionContainer, conn);
    WorkflowGroup wfGroup = (WorkflowGroup) wfGroupDAO.getObjectByID(TextUtility.parseIntegerObj(workflowSearchForm.getWorkflowGroupID()));
    request.setAttribute("workflowGroup", wfGroup);
    super.getListData(mapping, form, request, response);
  }

  public void deleteListData(ActionMapping mapping, AbstractSearchForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
    
    String[] selectedID = form.getBasicSelectedID();
    super.deleteListData(mapping, form, request, response);
    //Cancel the Schedule Jobs
    for (int i = 0; i < selectedID.length; i++) {    
      if (!Utility.isEmpty(selectedID[i])) {            
       // Delete schedule job when a workflow record is deleted
        WorkflowScheduleTriggersDAObject triggerDAO = new WorkflowScheduleTriggersDAObject(this.getSessionContainer(request), this.getConnection(request));
        List triggerList = triggerDAO.getListByWorkflowRecordID(new Integer(selectedID[i]) );
        for (int j = 0; j < triggerList.size(); j++) {
          WorkflowScheduleTriggers trigger = (WorkflowScheduleTriggers)triggerList.get(j);
        
          //Cancel the Schedule Job
          try {
            log.debug("=== Cancel Schedule_Job ===");
            org.quartz.Scheduler sched = com.dcivision.framework.SchedulerFactory.getScheduler();
          
            log.debug("JOB:"+GlobalConstant.JOB_PREFIX_WORKFLOW_SCHEDULE + trigger.getID() +":" +
              GlobalConstant.JOB_PREFIX_WORKFLOW_SCHEDULE + "GROUP");
          
            sched.unscheduleJob( GlobalConstant.JOB_PREFIX_WORKFLOW_SCHEDULE + trigger.getID(),
              GlobalConstant.JOB_PREFIX_WORKFLOW_SCHEDULE + "GROUP" );
          } catch (SchedulerException se) {
            log.debug("=== Cancel Schedule_Job Fail ===");
            throw new ApplicationException(WorkflowErrorConstant.CANCEL_SCHEDULE_JOB_FAIL);
          }
        
        }
        
//      added by nancy
        WorkflowStepManager wsManager=new WorkflowStepManager(this.getSessionContainer(request), this.getConnection(request));
        wsManager.deleteStepByRecordID(new Integer(selectedID[i]));

        //end
         
      }
    }
    
  }
  
}
